import React from 'react';
import Toast from 'antd-mobile/lib/toast';
import className from 'classnames';
import find from 'lodash/find';
import HeaderNav from 'shared/components/HeaderNav';
import Menu from 'shared/components/Menu';
import { fetchCategoryList } from 'shared/api';
import getUrlParam from 'shared/utils/getUrlParam';
import ProductList from './ProductList';
import './index.less';

export default class AllProduct extends React.PureComponent {
  state = {
    data: [],
    categoryId: '',
    title: ''
  }
  componentDidMount() {
    Toast.loading('数据加载中', 5)
    const defaultCategoryId = getUrlParam('defaultCategoryId');
    this.filterCategoryId = getUrlParam('filterCategoryId');

    fetchCategoryList().then(({ data }) => {
      Toast.hide()
      let defaultCategory
      if (defaultCategoryId) {
        defaultCategory = find(data, { category_id: defaultCategoryId })
      }
      const { title, category_id } = defaultCategory || data[0];

      this.props.history.push(`/allProduct?defaultCategoryId=${category_id}&filterCategoryId=${category_id}`)
      if (!isMobile) {
        const { pathname } = __self.history.location
        if (pathname.indexOf('allProduct') !== -1) {
          location.href = `${window.url}/promotion?category_id=${category_id}&category_id2=${this.filterCategoryId || category_id}`;
          return;
        }
      }

      this.setState({ data, categoryId: category_id, title })
    })
  }

  componentWillUnmount() {
    Toast.hide()
  }

  render() {
    const { data, categoryId, title } = this.state;
    return (
      [
        <HeaderNav key="HeaderNav" />,
        <div className="all-product" key="all-product">
          <ul className="all-product-sidebar">
            {
              data.map(({ category_id, title }, index) => (
                <li
                  key={index}
                  data-id={category_id}
                  onClick={() => {
                    this.setState({ categoryId: category_id, title })
                    gloablMonitor([`商品列表页-${title}`, title])
                    this.props.history.push(`/allProduct?defaultCategoryId=${category_id}&filterCategoryId=${category_id}`)
                  }}
                  className={className({active: category_id === categoryId})}
                >
                  {title}
                </li>)
              )
            }
          </ul>
          {
            categoryId &&
            <ProductList
              history={this.props.history}
              categoryId={categoryId}
              filterCategoryId={getUrlParam('filterCategoryId')}
              title={title}
            />
          }
        </div>,
        <Menu key="menu" />
      ]
    )
  }
}